﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BaFangSpider.Stock
{
    public class StockMonitorService : MonitorService
    {
        Dictionary<string, StockAnalyzer> stocks;
        List<string> stockNumbers;
        DataManager dataMan = new DataManager("Stock\\stocks.xml", typeof(List<string>));

        private StockMonitorService()
        {
            this.mailAddress = MailAccounts.GetInstance().Stock;
            stockNumbers = dataMan.LoadData() as List<string>;
            if (stockNumbers == null)
            {
                stockNumbers = new List<string>();
            }

        }

        private static StockMonitorService instance = null;

        public static StockMonitorService GetInstance()
        {
            if (instance == null)
            {
                instance = new StockMonitorService();
            }
            return instance;
        }

        public override void Start()
        {
            base.Start();
            this.checkServiceTimer.Stop();

            stocks = new Dictionary<string, StockAnalyzer>(stockNumbers.Count + 20);
            foreach (string number in stockNumbers)
            {
                stocks.Add(number, new StockAnalyzer(number, "", this.mailAddress));
            }
        }

        public override void Stop()
        {
            base.Stop();
            foreach (StockAnalyzer an in this.stocks.Values)
            {
                an.Dispose();
            }
        }

        protected override void UpdateListenserRegisteredService(string interest, string content)
        {
            // TODO: 数据 validation
            base.UpdateListenserRegisteredService(interest, content);

            // Remove originals
            foreach (StockAnalyzer an in this.stocks.Values)
            {
                an.RemoveLister(interest);
            }

            // add new
            if (!string.IsNullOrEmpty(content))
            {
                StockService service = ServiceBase.CreateFromString<StockService>(content) as StockService;
                if (service != null)
                {
                    foreach (StockServiceEntity entity in service.Entities)
                    {
                        if (!stocks.ContainsKey(entity.StockId))
                        {
                            stocks.Add(entity.StockId, new StockAnalyzer(entity.StockId, entity.StockName, this.mailAddress));
                            stockNumbers.Add(entity.StockId);
                            dataMan.SaveData(this.stockNumbers);
                        }
                        StockAnalyzer an = this.stocks[entity.StockId];
                        an.AddListener(interest, double.Parse(entity.HighPrice), double.Parse(entity.LowPrice));
                    }
                }
            }
        }
    }
}
